package com.golddaymicromall.activity.setting.personal;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.model.HttpModel;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.golddaymicromall.util.Util;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;

public class UpdateAvatarActivity extends BaseActivity implements View.OnClickListener {

    private static final int CAMERA_REQUEST_CODE = 222;
    private static final int PICTURE_REQUEST_CODE = 222;
    Util util = new Util();

    /**
     * 上传图片的宽度和高度
     */
    private int mWH = 90;// 单位dp
    private ImageView mIvImageView;
    private Button mBtnCamera;
    private Button mBtnPicture;
    private LinearLayout mAvatarBack;
    Bitmap bitmap1;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_update_avatar);
        mWH = (int) (getResources().getDisplayMetrics().density * mWH);
        initView();
        String headImgName = SPUtils.get(getApplicationContext(), "headImg", "").toString();
        if (!"".equals(headImgName)) {
            Glide.with(this)
                    .load(HttpModel.HEADIMGURL + headImgName).placeholder(R.drawable.me_denglu_head)
                    .into(mIvImageView);
        }

    }

    private void initView() {
        mIvImageView = (ImageView) findViewById(R.id.iv_image);
        mBtnCamera = (Button) findViewById(R.id.btn_camera);
        mBtnPicture = (Button) findViewById(R.id.btn_picture);
        mAvatarBack = (LinearLayout) findViewById(R.id.avatar_back);
        mBtnCamera.setOnClickListener(this);
        mBtnPicture.setOnClickListener(this);
        mAvatarBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avatar_back:
                finish();
                break;
            case R.id.btn_camera:
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 请求拍照的Action
                // 在onActivityResult中处理拍照结果
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
                break;
            case R.id.btn_picture:
                Intent intentnew = new Intent();
                intentnew.addCategory(Intent.CATEGORY_OPENABLE);
                intentnew.setType("image/*");
                //根据版本号不同使用不同的Action
               if (Build.VERSION.SDK_INT <19) {
                   intentnew.setAction(Intent.ACTION_GET_CONTENT);
                }else {
                   intentnew.setAction(Intent.ACTION_OPEN_DOCUMENT);
                }
                startActivityForResult(intentnew, PICTURE_REQUEST_CODE);
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Uri uri = data.getData();
            Bitmap bitmap = null;
            String imgPath = null;
            if (null != uri) {
                ContentResolver resolver = this.getContentResolver();
                String[] columns = {MediaStore.Images.Media.DATA};
                Cursor cursor = null;
                cursor = resolver.query(uri, columns, null, null, null);
                if (Build.VERSION.SDK_INT > 18)// 4.4以后文件选择发生变化，判断处理
                {
                    if (requestCode == PICTURE_REQUEST_CODE)// 选择图片
                    {
                        imgPath = uri.getPath();
                        if (!TextUtils.isEmpty(imgPath)
                                && imgPath.contains(":")) {
                            String imgIndex = imgPath.split(":")[1];
                            cursor = resolver
                                    .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                            columns, "_id=?",
                                            new String[]{imgIndex}, null);
                        }
                    }
                }
                if (null != cursor && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(columns[0]);
                    imgPath = cursor.getString(columnIndex);
                    cursor.close();
                }
                if (!TextUtils.isEmpty(imgPath)) {
                    bitmap = genBitmap(imgPath);
                }
            } else if (requestCode == CAMERA_REQUEST_CODE)// 拍照
            {
                // 拍照时，注意小米手机不会保存图片到本地，只可以从intent中取出bitmap, 要特殊处理
                Object object = data.getExtras().get("data");
                if (null != object && object instanceof Bitmap) {
                    bitmap = (Bitmap) object;
                }
            }
            if (null != bitmap) {
                add(bitmap);
            }
        }
    }

    //通过给定的图片路径生成对应的bitmap
    public Bitmap genBitmap(String imgPath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;

        int widthSample = (int) (imageWidth / mWH);
        int heightSample = (int) (imageHeight / mWH);
        // 计算缩放比例
        options.inSampleSize = widthSample < heightSample ? heightSample
                : widthSample;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(imgPath, options);
    }

    /**
     * 根据bitmap压缩图片质量
     *
     * @param bitmap 未压缩的bitmap
     * @return 压缩后的bitmap
     */
    public static Bitmap cQuality(Bitmap bitmap) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        int beginRate = 100;
        //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOut);
        while (bOut.size() / 1024 / 1024 > 1) {  //如果压缩后大于100Kb，则提高压缩率，重新压缩
            beginRate -= 100;
            bOut.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, beginRate, bOut);
        }
        ByteArrayInputStream bInt = new ByteArrayInputStream(bOut.toByteArray());
        Bitmap newBitmap = BitmapFactory.decodeStream(bInt);
        if (newBitmap != null) {
            return newBitmap;
        } else {
            return bitmap;
        }
    }


    public String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 10, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public void add(Bitmap bitmap) {
        bitmap1 = bitmap;
        String logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        Bitmap bt = cQuality(bitmap);
        String pho = Bitmap2StrByBase64(bt);
        Log.e("pho", pho);
        pho = pho.replace("                                                                   ", "");
        pho = pho.replace("\n", "");
        pho = pho.replace("+", "<@@>");
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.user.upload");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("logid", logid);
        form.put("biao", "LOG");
        form.put("filestr", pho);
        form.put("type", ".png");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (!"".equals(response)) {
                        if (response.contains(".png")) {
                            SPUtils.put(UpdateAvatarActivity.this, "headImg", response.substring(1, response.length() - 1));
                            Toast.makeText(UpdateAvatarActivity.this, "上传头像成功", Toast.LENGTH_SHORT).show();
                            mIvImageView.setImageBitmap(bitmap1);
                        } else {
                            Toast.makeText(UpdateAvatarActivity.this, "上传头像失败,请重新尝试", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(UpdateAvatarActivity.this, "请求服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

}